<!doctype html>

<html lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>系统菜单管理</title>

    <link rel="stylesheet" type="text/css" href="/form/rest/webjars/extjs/4.2.1.883/resources/css/ext-all.css"/>

    <link href="/form/rest/webjars/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>

    <script src="/form/rest/webjars/extjs/4.2.1.883/bootstrap.js"></script>

    <script type="text/javascript" src="/form/rest/public/rowedit-fix.js"></script>

    <!--<script type="text/javascript" src="app.js"></script>-->

</head>
<body>
<script type="text/javascript">
    Ext.require(['Ext.data.*', 'Ext.form.*', 'Ext.tree.*', 'Ext.grid.*']);


    //查询参数预处理
    function beforeload(store, operation, eOpts) {
        console.log(store);
        console.log(operation);

        //排序参数预处理
        var sortstr = new Array();

        function sortArrayElements(element, index, array) {
            sortstr[index] = element.property + "," + element.direction;
        }

        operation.sorters.forEach(sortArrayElements);


        //将搜索条件放在store的baseParams中，每次加载都赋值
        //var new_params = { name: Ext.getCmp('search').getValue() };
        //Ext.apply(store.proxy.extraParams, "searchkeyword");
        //var params = {sthecstr:conditionstr};
        //Ext.apply(options.params, params);
        //store.baseParams = {limit: gridPageSize, filter: $('#txtFilter').val()};


        //翻页参数预处理，以及排序参数更新
        var params = {
            sort: sortstr,
            page: store.currentPage - 1
        };
        Ext.apply(store.proxy.extraParams, params);


    }

    Ext.define('Resource', {
        extend: 'Ext.data.Model',
        idProperty: 'pkId',
        fields: [{
            name: 'module',
            type: 'string'
        }, {
            name: 'name',
            type: 'string'
        }, {
            name: 'pid',
            type: 'string'
        }, {
            name: 'remark',
            type: 'string'
        }, {
            name: 'type',
            type: 'string'
        }, {
            name: 'url',
            type: 'string'
        }, {
            name: 'enabled',
            type: 'boolean'
        }, {
            name: 'leaf',
            type: 'boolean'
        }]
    });


    Ext.onReady(function () {
        var store = new Ext.data.TreeStore({
            autoDestroy: true,
            autoLoad: true,
            autoSync: true,
            model: Resource,
//            sorters: [{
//                property: 'name',
//                direction: 'ASC'
//            }],
            // 根节点的参数是parentId
            nodeParam: "rootId",
            // 根节点的参数值是0
            defaultRootId: 'resource', //异步加载id 与 修改Id 不一致的解决访问； 一次性生成数据可以解决叶子与主id 的关系；
            proxy: {
                type: 'rest',
                appendId: true,
                actionMethods: {
                    create: "POST",
                    read: "GET",
                    update: "PATCH",
                    destroy: "DELETE"
                },

                reader: {
                    type: 'json'
                    //,root : 'resource'
                },
                //url: '/form/rest/public/data/resource.json',
                api: { //rest 模式 修改删除需要增加appendId,查询不需要appendid
                    create: '/form/rest/resource',
                    read: '/form/rest/resource/menus?',
                    update: '/form/rest/resource',
                    destroy: '/form/rest/resource'
                },

                extraParams: {
                    path: 'jsontree'
                },
                listeners: {
                    exception: function (proxy, response, operation) {
                        console.log(response.responseText);
                        console.log(response.status);
                        //Ext.Msg.alert('ERROR', response.responseText + ' ' + response.statusText);

                        if (response.status === 403 || response.status === 401 || response.status === 500)
                            Ext.Msg.alert('ERROR', response.responseText + ' ' + response.statusText);
                    },
                    load: function (self, records) {
//                    // Filling Array of messages
                        console.log(records);
//                    var arr = [];
//                    console.log(records);
//                    console.log(records.rawData);
//                    console.log(records[0].raw._embedded.resource);
//
//                    for(m in records[0].raw._embedded.resource){
//                        var message = {
//                            message: records[0].raw._embedded.resource[m].resource,
//                            href:records[0].raw._embedded.resource[m]._links.self.href
//                        };
//                        arr.push(message);
//                    }
//                    view.setData(arr[0]);
                    },
                    // Each demo.UserModel instance will be automatically
//                // decorated with methods/properties of Ext.data.NodeInterface
//                // (i.e., a "node"). Whenever a UserModel node is appended
//                // to the tree, this TreeStore will fire an "append" event.
//                append: function( thisNode, newChildNode, index, eOpts ) {
//
//                    // If the node that's being appended isn't a root node, then we can
//                    // assume it's one of our UserModel instances that's been "dressed
//                    // up" as a node
//                    if( !newChildNode.isRoot() ) {
//                        newChildNode.set('leaf', true);
//
//                        newChildNode.set('text', newChildNode.get('name'));
//                        newChildNode.set('icon', newChildNode.get('profile_image_url'));
//                    }
//                }
                }
            },
            folderSort: false  //获取数据的时候所有字段都产生排序

        });

        var rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
            listeners: {
                cancelEdit: function (rowEditing, context) {
                    // Canceling editing of a locally added, unsaved record: remove it
                    if (context.record.phantom) {
                        store.remove(context.record);
                    }
                }
            }
        });

        var grid = Ext.create('Ext.tree.Panel', {
            renderTo: document.body,
            plugins: [rowEditing],
            width: 700,
            height: 500,
            frame: true,
            title: '系统菜单管理',
            useArrows: true,
            rootVisible: false,
            multiSelect: true,
            singleExpand: true,

            store: store,
            viewConfig: {
                plugins: {
                    ptype: 'treeviewdragdrop',
                    containerScroll: true
                }
            },
            iconCls: 'icon-user',
            columns: [{
                xtype: 'treecolumn', //this is so we know which column will show the tree
                text: '名称',
                flex: 2,
                sortable: true,
                dataIndex: 'name',
                editor: {
                    allowBlank: false
                }
            },
                {
                    //we must use the templateheader component so we can use a custom tpl
                    //xtype: 'templatecolumn',
                    //xtype: 'treecolumn',
                    text: '编码',
                    flex: 1,
                    sortable: true,
                    dataIndex: 'module',
                    align: 'center',
                    editor: {
                        allowBlank: false
                    }
//                ,
//                //add in the custom tpl for the rows
//                tpl: Ext.create('Ext.XTemplate', '{duration:this.formatHours}', {
//                    formatHours: function (v) {
//                        if (v < 1) {
//                            return Math.round(v * 60) + ' mins';
//                        } else if (Math.floor(v) !== v) {
//                            var min = v - Math.floor(v);
//                            return Math.floor(v) + 'h ' + Math.round(min * 60) + 'm';
//                        } else {
//                            return v + ' hour' + (v === 1 ? '' : 's');
//                        }
//                    }
//                })
                }
                ,

                {
                    //xtype: 'checkcolumn',
                    //header: '父节点编码',
                    text: '父节点',
                    flex: 1,
                    dataIndex: 'pid',
                    editor: {
                        allowBlank: false
                    }
//                    width: 55,
//                    stopSelection: false,
//                    menuDisabled: true
                },
                {
                    text: '链接地址',
                    flex: 2,
                    dataIndex: 'url',
                    sortable: true,
                    editor: {
                        allowBlank: false
                    }
                },
                {
                    text: 'Delete',
                    width: 55,
                    menuDisabled: true,
                    xtype: 'actioncolumn',
                    tooltip: '删除',
                    align: 'center',
                    icon: '../resources/images/icons/delete.png',
                    handler: function (grid, rowIndex, colIndex, actionItem, event, record, row) {
                        // Ext.Msg.alert('Delete' + (record.get('done') ? ' completed task' : ''), record.get('task'));
                        record.remove(true);
                        store.sync();


                    },
                    // Only leaf level tasks may be edited
                    isDisabled: function (view, rowIdx, colIdx, item, record) {
                        return !record.data.leaf;
                    }
                }],

            addNode: function (node, leaf) {
                //如果选中的是叶子节点，就添加在它的父节点；
                console.log(node);
                console.log(node.parentNode);

                if (node.childNodes.length<=0){
                    node = node.parentNode;
                }

                console.log(node);

                if (node && !node.leaf) {
                    node.expand();

                    console.log("add node :" + node);
                    console.log("add node :" + node.data.module);
                    console.log("add node :" + node.lastChild.data.module);


                    var lastnode = node.lastChild.data.module;

                    //通过正则实现id 的自增
                    var re1 = /([1-9]*)/;

                    var str = lastnode.module;
                    var arr1 = re1.exec(str)[0];
                    var arr2 = (parseInt(arr1) + 1).toString();
                    console.log("=======" + str);
                    console.log("=======" + arr1);
                    console.log("=======" + arr2);

                    var result = str.replace(arr1, arr2);

                    console.log("=======" + result);

                    var newList = Ext.create('Resource', {
                        pid: node.data.module,
                        module: result,
                        name: 'New 节点',
                        type: 'yy',
                        url: 'test.com/test',
                        remark: '新增节点',
                        enabled: true,
                        leaf: true
//                        ,
//                        loaded: true
                    });

                    node.appendChild(newList);
                    selectionModel = grid.getSelectionModel();
                    selectionModel.select(newList);
                    rowEditing.startEdit(newList, 0);


                } else {

                    Ext.Msg.alert('请选择一个父节点');

                }
            },
            dockedItems: [{
                xtype: 'toolbar',
                items: [{
                    text: 'Add-叶节点',
                    iconCls: 'icon-add',
                    handler: function () {
                        // empty record
                        var node = grid.getSelectionModel().getSelection()[0] || grid.getRootNode();
                        grid.addNode(node, true);
//                        store.reload();
//                        store.sync();

                    }
                }, {
                    text: 'Add-支节点',
                    iconCls: 'icon-add',
                    handler: function () {
                        // empty record
                        var node = grid.getSelectionModel().getSelection()[0] || grid.getRootNode();
                        grid.addNode(node, false);
//                        store.sync();

                    }
                }, '-', {
                    itemId: 'delete',
                    text: 'Del节点',
                    iconCls: 'icon-delete',
                    disabled: true,
                    handler: function () {
                        var selection = grid.getView().getSelectionModel().getSelection()[0];
                        if (selection) {
                            selection.remove(true);
//                            store.sync();
                        }
                    }
                }]
            }]
        });

        //枝节点不允许删除
        grid.getSelectionModel().on('selectionchange', function (selModel, selections) {
            console.log(selModel);
            console.log(selections);//选中多条记录
//            console.log(selections[0].data.leaf);
            var node = selections[0];

            if (selections.length == 0 || node.leaf || node.childNodes.length == 0) {
                grid.down('#delete').setDisabled(false);
            } else {
                grid.down('#delete').setDisabled(true);
            }
        });

    });


</script>

</body>
</html>